import { Router } from 'express'

const router = Router()

// 内存模拟公告数据
let announcements = [
  { id: 1, title: '示例公告', content: '这是一个公告内容', status: 1, publisher: '管理员', publishTime: new Date() }
]

// 获取公告列表（支持分页和标题筛选）
router.get('/', (req, res) => {
  try {
    let { page = 1, limit = 10, title = '', status } = req.query
    page = Math.max(Number(page) || 1, 1)
    limit = Math.max(Number(limit) || 10, 1)
    title = String(title || '')

    let filtered = Array.isArray(announcements)
      ? announcements.filter(a =>
          (!!a && typeof a.title === 'string' && a.title.includes(title)) &&
          (status === undefined || status === '' || a.status == Number(status))
        )
      : []

    const start = (page - 1) * limit
    const end = start + limit
    res.json({
      code: 0,
      message: 'success',
      total: Array.isArray(filtered) ? filtered.length : 0,
      items: Array.isArray(filtered) ? filtered.slice(start, end) : []
    })
  } catch (err) {
    console.error('获取公告列表出错:', err)
    res.status(500).json({ code: 1, message: '服务器内部错误', error: String(err) })
  }
})

// 新增公告（只保留一个实现）
router.post('/', (req, res) => {
  const { title, content = '', status = 0, publisher = '管理员' } = req.body
  if (!title) {
    return res.status(400).json({ code: 1, message: '标题不能为空' })
  }
  const id = announcements.length ? (announcements[announcements.length - 1]?.id ?? 0) + 1 : 1
  const publishTime = new Date()
  const newAnnouncement = { id, title, content, status, publisher, publishTime }
  announcements.push(newAnnouncement)
  return res.json({ code: 0, message: '新增成功', item: newAnnouncement })
})

// 更新公告
router.put('/:id', (req, res) => {
  const idx = announcements.findIndex(a => a.id === Number(req.params.id))
  if (idx !== -1) {
    announcements[idx] = { ...announcements[idx], ...req.body }
    res.json({ code: 0, message: '更新成功', item: announcements[idx] })
  } else {
    res.status(404).json({ code: 1, message: '未找到公告' })
  }
})

// 删除公告
router.delete('/:id', (req, res) => {
  const idx = announcements.findIndex(a => a.id === Number(req.params.id))
  if (idx !== -1) {
    announcements.splice(idx, 1)
    res.json({ code: 0, message: '删除成功' })
  } else {
    res.status(404).json({ code: 1, message: '未找到公告' })
  }
})

export default router
